package com.express.boot.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.express.boot.config.security.SHA256Util;
import com.express.boot.domain.Role;
import com.express.boot.domain.User;
import com.express.boot.domain.User_role;
import com.express.boot.mapper.UserMapper;
import com.express.boot.mapper.User_roleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserService extends ServiceImpl<UserMapper, User> {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private User_roleService user_roleService;

    @Autowired
    private User_roleMapper userRoleMapper;

    /**
     * @param username
     * @return 用户信息及其拥有的权限
     */
    public User loadUserByUsername(String username) {

//        user.setRoles(userMapper.getUserRolesByUid(user.getId()));
        return userMapper.loadUserByUsername(username);
    }

    /**
     * 分页查询
     *
     * @param pageNum 当前页数
     * @param size    当前页有多少条数据
     * @return
     */
    public List<User> userList(Integer pageNum, Integer size, String query) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("username" , query);
        IPage<User> page = userMapper.selectPage(new Page<>(pageNum, size), queryWrapper);
        List<User> users = page.getRecords();
        return users;
    }

    /**
     * 添加用户
     *
     * @param user 用户主体
     * @return 操作多少条数据
     */
    public Integer addUser(User user) {
        String pawd = SHA256Util.sha256(user.getPassword(), user.getSalt());

        user.setPassword(pawd);
        int i = userMapper.insertUer(user);
        int uid = user.getId();
        int rid = Integer.parseInt(user.getRoleName());

        QueryWrapper<User_role> query = new QueryWrapper<>();

        query.eq("uid" , uid);
        user_roleService.remove(query);
        User_role ur = new User_role();

        //更新user表
        User user1 = getById(uid);
        Role role = roleService.getById(rid);
        //在user表中设置名称
        user1.setRoleName(role.getNameZh());
        userService.updateById(user1);

        //更新角色
        ur.setUid(uid);
        ur.setRid(rid);
        Boolean i1 = user_roleService.save(ur);

        return i;
    }


    public List<User> selectUserList(User user) {
        return userMapper.selectUserList(user);
    }
}
